package com.etoak.service.impl;

import cn.hutool.json.JSONUtil;
import com.etoak.common.core.constant.CommonConstant;
import com.etoak.common.redis.RedisService;
import com.etoak.common.web.context.LoginContext;
import com.etoak.entity.Cart;
import com.etoak.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    RedisService redisService;

    @Override
    public void saveOrUpdate(Cart cart) {
        redisService.hset(getRedisKey(),
                cart.getDishesId().toString(),
                JSONUtil.toJsonStr(cart));
    }

    @Override
    public List<Cart> getList() {

        return redisService.hvals(getRedisKey())
                .stream().map(json -> JSONUtil.toBean(json, Cart.class))
                .toList();
    }

    @Override
    public void deleteDishes(String dishId) {
        redisService.hdel(getRedisKey(), dishId);
    }

    @Override
    public void clear() {
        redisService.del(getRedisKey());
    }

    /**
     * 获取购物车的redis key => cart:user:userId
     */
    private String getRedisKey() {
        return CommonConstant.REDIS_CART_KEY + LoginContext.getUserId();
    }
}
